package asia.doing.service.front;

import asia.doing.entity.ArticleCategory;
import asia.doing.entity.Category;
import asia.doing.mapper.CategoryMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;

@Service(value = "frontCategoryService")
public class CategoryService {

    @Resource
    private CategoryMapper categoryMapper;


    public List<Category> selectCategory(Category category) {
        List<Category> categories = categoryMapper.selectAll(category);
        for (Category category1 : categories) {
            //根据分类id查询所有的文章
            Integer id1 = category1.getId();
            ArticleCategory articleCategory = new ArticleCategory();
            articleCategory.setCategoryId(id1);
            List<ArticleCategory> articleIds = categoryMapper.selectByArtOrCaId(articleCategory);
            //声明一个Set列表
            HashSet<Integer> articleIdSets = new HashSet<>();
            for (ArticleCategory articleId : articleIds) {
                articleIdSets.add(articleId.getArticleId());
            }
            Integer[] articleIdsArray = articleIdSets.toArray(new Integer[articleIdSets.size()]);
            category1.setArticles(articleIdsArray);
        }
        return categories;

    }

    public PageInfo<Category> selectPage(Category category, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Category> categories = categoryMapper.selectAll(category);

        for (Category category1 : categories) {
            //根据分类id查询所有的文章
            Integer id = category1.getId();
            ArticleCategory articleCategory = new ArticleCategory();
            articleCategory.setCategoryId(id);
            List<ArticleCategory> articleIds = categoryMapper.selectByArtOrCaId(articleCategory);
            //声明一个Set列表
            HashSet<Integer> articleIdSets = new HashSet<>();
            for (ArticleCategory articleId : articleIds) {
                articleIdSets.add(articleId.getArticleId());
            }
            Integer[] articleIdsArray = articleIdSets.toArray(new Integer[articleIdSets.size()]);
            category1.setArticles(articleIdsArray);
        }

        PageInfo<Category> pageInfo = PageInfo.of(categories);
        return pageInfo;
    }
}
